<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace app\user\model;

use think\Db;
use think\Model;
use think\Validate;
use tree\Tree;

class UserModel extends Model
{
    /**
     * 判断用户是否存在
     * @param $condition
     * @return bool|int
     */
    public function checkUser($condition)
    {
        if(!is_array($condition) || count($condition) < 0){
            return false;
        }
        $result = $this->where($condition)->find();
        if(isset($result) && !empty($result)){
            //该用户已存在
            $user_exist  = 1;
        }else{
            //没有该用户
            $user_exist = 2;
        }
        return $user_exist;
    }

    /**
     * 获取用户所属的学校
     * @param $uid
     * @param int $shop_id
     * @return array|bool|false|\PDOStatement|string|\think\Collection
     */
    public function getSchoolByUid($uid, $shop_id=1)
    {
        if(empty($uid) || !is_numeric($uid)){
            return false;
        }
        //获取学校
        $condition = [
            'us.shop_id' => $shop_id,
            'us.uid' => $uid,
        ];
        $schools = Db::name('user_school')->alias('us')
            ->field('sc.id as school_id,sc.name as school_name')
            ->join('school sc','us.school_id=sc.id')
            ->where($condition)
            ->select();
        if(!$schools->isEmpty()){
            $schools = $schools->toArray();
        }else{
            $schools = [];
        }

        return $schools;
    }
    
    public function doMobile($user)
    {
        $userQuery = Db::name("user");

        $where = [
            'mobile' => ['=', $user['mobile']],
            'user_type' => ['=', 2],//前台用户
        ];
        $result = $userQuery->where($where)->find();

        if (!empty($result)) {
            if (cmf_compare_password($user['user_pass'], $result['user_pass'])) {
                session('user', $result);
                $data = [
                    'last_login_time' => time(),
                    'last_login_ip'   => get_client_ip(0, true),
                ];
                $userQuery->where('id', $result["id"])->update($data);
                return 0;
            }
            return 1;
        }
        return 2;
    }

    public function doName($user)
    {
        $userQuery = Db::name("user");

        $where = [
            'user_login' => ['=', $user['user_login']],
            'user_type' => ['=', 2],//前台用户
        ];
        $result = $userQuery->where($where)->find();

        if (!empty($result)) {
            if (cmf_compare_password($user['user_pass'], $result['user_pass'])) {
                session('user', $result);
                $data = [
                    'last_login_time' => time(),
                    'last_login_ip'   => get_client_ip(0, true),
                ];
                $userQuery->where('id', $result["id"])->update($data);
                return 0;
            }
            return 1;
        }
        return 2;
    }

    public function doEmail($user)
    {
        $userQuery = Db::name("user");

        $where = [
            'user_email' => ['=', $user['user_email']],
            'user_type' => ['=', 2],//前台用户
        ];
        $result = $userQuery->where($where)->find();

        if (!empty($result)) {
            if (cmf_compare_password($user['user_pass'], $result['user_pass'])) {
                session('user', $result);
                $data = [
                    'last_login_time' => time(),
                    'last_login_ip'   => get_client_ip(0, true),
                ];
                $userQuery->where('id', $result["id"])->update($data);
                return 0;
            }
            return 1;
        }
        return 2;
    }

    public function registerEmail($user)
    {
        $userQuery = Db::name("user");
        $result    = $userQuery->where('user_email', $user['user_email'])->find();
        if (empty($result)) {
            $data   = [
                'user_login'      => '',
                'user_email'      => $user['user_email'],
                'mobile'          => '',
                'user_nickname'   => '',
                'user_pass'       => cmf_password($user['user_pass']),
                'last_login_ip'   => get_client_ip(0, true),
                'create_time'     => time(),
                'last_login_time' => time(),
                'user_status'     => 1,
                "user_type"       => 2,
            ];
            $userId = $userQuery->insertGetId($data);
            $date   = $userQuery->where('id', $userId)->find();
            cmf_update_current_user($date);
            //绑定学生家长
            $res = $this->bindParent($user['user_email']);
            if(!$res){
                //账号绑定失败
                return 3;
            }

            return 0;
        }
        return 1;
    }

    public function registerMobile($user)
    {
        $result = Db::name("user")->where('mobile', $user['mobile'])->find();
        if (empty($result)) {
            $data   = [
                'user_login'      => '',
                'user_email'      => $user['user_email'],//(steven)增加邮箱必填
                'mobile'          => $user['mobile'],
                'user_nickname'   => '',
                'user_pass'       => cmf_password($user['user_pass']),
                'last_login_ip'   => get_client_ip(0, true),
                'create_time'     => time(),
                'last_login_time' => time(),
                'user_status'     => 1,
                "user_type"       => 2,//会员
            ];
            $userId = Db::name("user")->insertGetId($data);
            $data   = Db::name("user")->where('id', $userId)->find();
            cmf_update_current_user($data);
            //绑定学生家长
            $res = $this->bindParent($user['mobile']);
            if(!$res){
                //账号绑定失败
                return 3;
            }
            return 0;
        }
        return 1;
    }

    /**
     * 绑定学生家长
     * @param $condition
     * @param string $msg
     * @return bool
     */
    public function bindParent($condition, &$msg='')
    {
        if (Validate::is(trim($condition), 'email')) {
            //通过邮箱获取用户
            $user = Db::name('user')->where('user_email','eq', trim($condition))->find();
            if(count($user) <= 0){
                $msg = '用户不存在';
                return false;
            }
            //查看学生家长
            $student = Db::name('student')->where('email','eq', trim($condition))->find();
            if(count($student) > 0){
                //绑定家长
                Db::name('student')->where('email','eq', trim($condition))->update(['u_id'=>$user['id']]);
            }

        } elseif (preg_match('/(^(13\d|14[57]|15[^4\D]|17[13678]|18\d)\d{8}|170[^346\D]\d{7})$/', trim($condition))) {
            //通过手机号获取用户
            $user = Db::name('user')->where('mobile','eq', trim($condition))->find();
            if(count($user) <= 0){
                $msg = '用户不存在';
                return false;
            }
            //查看学生家长
            $student = Db::name('student')->where('mobile','eq', trim($condition))->find();
            if(count($student) > 0){
                //绑定家长
                Db::name('student')->where('mobile','eq', trim($condition))->update(['u_id'=>$user['id']]);
            }
        } else {
            $msg = '参数有误';
            return false;
        }

        return true;
    }

    /**
     * 通过邮箱重置密码
     * @param $email
     * @param $password
     * @return int
     */
    public function emailPasswordReset($email, $password)
    {
        $result = $this->where('user_email', $email)->find();
        if (!empty($result)) {
            $data = [
                'user_pass' => cmf_password($password),
            ];
            $this->where('user_email', $email)->update($data);
            return 0;
        }
        return 1;
    }

    /**
     * 通过手机重置密码
     * @param $mobile
     * @param $password
     * @return int
     */
    public function mobilePasswordReset($mobile, $password)
    {
        $userQuery = Db::name("user");
        $result    = $userQuery->where('mobile', $mobile)->find();
        if (!empty($result)) {
            $data = [
                'user_pass' => cmf_password($password),
            ];
            $userQuery->where('mobile', $mobile)->update($data);
            return 0;
        }
        return 1;
    }

    public function editData($user)
    {
        $userId = cmf_get_current_user_id();
        //(steven)取消用户生日
        //$user['birthday'] = strtotime($user['birthday']);
        $userQuery = Db::name("user");
        if ($userQuery->where('id', $userId)->update($user)) {
            $data = $userQuery->where('id', $userId)->find();
            cmf_update_current_user($data);
            return 1;
        }
        return 0;
    }

    /**
     * 用户密码修改
     * @param $user
     * @return int
     */
    public function editPassword($user)
    {
        $userId    = cmf_get_current_user_id();
        $userQuery = Db::name("user");
        if ($user['password'] != $user['repassword']) {
            return 1;
        }
        $pass = $userQuery->where('id', $userId)->find();
        if (!cmf_compare_password($user['old_password'], $pass['user_pass'])) {
            return 2;
        }
        $data['user_pass'] = cmf_password($user['password']);
        $userQuery->where('id', $userId)->update($data);
        return 0;
    }

    public function comments()
    {
        $userId               = cmf_get_current_user_id();
        $userQuery            = Db::name("Comment");
        $where['user_id']     = $userId;
        $where['delete_time'] = 0;
        $favorites            = $userQuery->where($where)->order('id desc')->paginate(10);
        $data['page']         = $favorites->render();
        $data['lists']        = $favorites->items();
        return $data;
    }

    public function deleteComment($id)
    {
        $userId              = cmf_get_current_user_id();
        $userQuery           = Db::name("Comment");
        $where['id']         = $id;
        $where['user_id']    = $userId;
        $data['delete_time'] = time();
        $userQuery->where($where)->update($data);
        return $data;
    }

    /**
     * 绑定前台用户手机号
     */
    public function bindingMobile($user)
    {
        $userId      = cmf_get_current_user_id();
        $mobileCount = $this->where(['user_type'=>2,'mobile'=>$user['mobile']])->count();
        if ($mobileCount > 0) {
            return 2; //手机已经存在
        } else {
            Db::name("user")->where('id', $userId)->update($user);
            $data = Db::name("user")->where('id', $userId)->find();
            cmf_update_current_user($data);
            //绑定学生家长
            $this->bindParent($user['mobile']);
        }

        return 0;
    }

    /**
     * 绑定前台用户邮箱
     */
    public function bindingEmail($user)
    {
        $userId     = cmf_get_current_user_id();
        $emailCount = $this->where(['user_type'=>2,'user_email'=>$user['user_email']])->count();
        if ($emailCount > 0) {
            return 2; //邮箱已经存在
        } else {
            Db::name("user")->where('id', $userId)->update($user);
            $data = Db::name("user")->where('id', $userId)->find();
            cmf_update_current_user($data);
            //绑定学生家长
            $this->bindParent($user['user_email']);
        }

        return 0;
    }
    /**
     * 添加的家长用户管理
     * @param shan 2017/5/4
     */
    public function statusCategory($selectId=0)
    {
        $where=[];
        $categories = $this->where($where)->select()->toArray();
        $newCategories = [];
        foreach ($categories as $item) {
            $item['selected'] = $selectId == $item['id'] ? "selected" : "";
            array_push($newCategories, $item);
        }
        $tree=new Tree();

//        echo "<pre>";
//        var_dump($newCategories);
        $tree->init($newCategories);
        $str= '<option value=\"{$id}\" {$selected}>{$spacer}{$name}</option>';
//        $treeStr=   $tree->getTreeCategory(0,$str);;
    }
}
